<%@page import="com.mycity.jsonops.PostOps"%>
<%@page import="com.mycity.dao.UserTab"%>
<%@page import="com.mycity.dao.PostTab"%>
<%
    UserTab user = (UserTab) session.getAttribute("user_info");
     PostTab[] posts = (PostTab[]) PostOps.getPostsByUserId(user.getUserId());
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>My City -- Create a Post</title>
        <meta name='generator' content='http://www.fg-a.com' />
        <meta http-equiv="cache-control" content="no-cache" />
        <!-- Main style -->
        <link rel="stylesheet" href="/MyCityWeb/css/style.css" type="text/css" />
        <link href="http://www.gstatic.com/freebase/suggest/4_1/suggest.min.css" rel="stylesheet" type="text/css"/>
        <link href="/MyCityWeb/js/tag-it-master/css/jquery.tagit.css" rel="stylesheet" type="text/css">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://www.gstatic.com/freebase/suggest/4_1/suggest.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
        <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
        <script src="/MyCityWeb/js/tag-it-master/js/tag-it.js" type="text/javascript" charset="utf-8"></script>
        <script
            src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
        </script>

        <script type="text/javascript">
            function validateForm() {
                var z = document.forms['PostCreate']['nplace'].value
                var y = document.forms['PostCreate']['question'].value
                var x = document.forms['PostCreate']['tags'].value
                if (y == null || y == "" ||  x == null || x == "" ||
                    z == null || z == ""  )
                    return false;
            }
        </script>

        <script type="text/javascript">
            var myCenter = new google.maps.LatLng(41.00527, 28.977);
            var marker;
            var map;
            var curpos;
            var markers = [];
            var browserSupportFlag = new Boolean();
            function initialize()
            {
                var mapProp = {
                    center: myCenter,
                    zoom: 20,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);

                google.maps.event.addListener(map, 'click', function(event) {
                    deleteMarkers();
                    placeMarker(event.latLng);
                });
                if (navigator.geolocation) {
                    browserSupportFlag = true;
                    navigator.geolocation.getCurrentPosition(function(position) {
                        curpos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                        map.setCenter(curpos);
                        placeMarker(curpos);
                    }, function() {
                        handleNoGeolocation(browserSupportFlag);
                    });
                }
                // Browser doesn't support Geolocation
                else {
                    browserSupportFlag = false;
                    handleNoGeolocation(browserSupportFlag);
                }

                function handleNoGeolocation(errorFlag) {
                    if (errorFlag == true) {
                        alert("Geolocation service failed.");
                        curpos = myCenter;
                    } else {
                        alert("Your browser doesn't support geolocation. We've placed you in Istanbul.");
                        curpos = myCenter;
                    }
                    placeMarker(curpos);
                    map.setCenter(curpos);
                }
            }
            function addMarkerListener(m, id) {
                google.maps.event.addListener(m, 'click', function() {
                    document.getElementById("id_lat").value = id;
                    $('#iplace').val(m.getTitle());
                    map.setCenter(m.getPosition());
                    map.setZoom(20);
                });

            }
            function placeMarker(location) {
                if (marker) {
                    marker.setPosition(location);
                } else {
                    marker = new google.maps.Marker({
                        position: location,
                        title: "Me",
                        map: map
                    });

                }
                map.setCenter(marker.getPosition());
                map.setZoom(17);
                getPlaces(location);
            }


            function getPlaces(locpos) {
                $.ajax({
                    dataType: "jsonp",
                    url: "https://api.instagram.com/v1/locations/search?lat=" + locpos.lat() + "&lng=" + locpos.lng() + "&client_id=bbe7c585542f41dd924f1c96e63bc591",
                    success: function(data) {
                        var index;
                        markers = [];
                        var size = Math.min(data.data.length, 12);
                   
                        for (index = 0; index < size; ++index) {
                            m = new google.maps.Marker({
                                position: new google.maps.LatLng(data.data[index].latitude, data.data[index].longitude),
                                title: data.data[index].name,
                                map: map
                            });
                            addMarkerListener(m, data.data[index].id);
                            markers.push(m);
                        }
                    }
                });
            }

            function setAllMap(map) {
                for (var i = 0; i < markers.length; i++) {
                    markers[i].setMap(map);
                }
            }

// Removes the markers from the map, but keeps them in the array.
            function clearMarkers() {
                setAllMap(null);
            }

// Shows any markers currently in the array.
            function showMarkers() {
                setAllMap(map);
            }

// Deletes all markers in the array by removing references to them.
            function deleteMarkers() {
                clearMarkers();
                markers = [];
            }
            google.maps.event.addDomListener(window, 'load', initialize);
        </script>


        
        
         <script type="text/javascript">
            $(document).ready(function() {
                    $(function() {
                        $("#tags").tagit({
                             allowSpaces: true,
                        tagSource: function( request, response ) {
                            $.ajax({
                            url: "https://www.googleapis.com/freebase/v1/search",
                            dataType: "jsonp",
                            data: {
                                    limit: 12,
                                    query: request.term
                            },
                            success: function( data ) {
                                response( $.map( data.result, function( item ) {
                                var temp = item.notable;
                                if(typeof temp != 'undefined'){
                                        temp = (temp["name"]);
                                }
                                else{
                                temp = "";
                                }
                                return {
                                    label: item.name + "(" + temp + ")",
                                    value: item.name + "(" + temp + ")"
                                };
                           }));
                           }
                                });
                                }
                                });
                                });
                                });
         </script>

        <script>

            function upload(file) {

                var fd = new FormData();
                fd.append("image", file);
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "https://api.imgur.com/3/image", true);
                xhr.setRequestHeader("Authorization", "Client-ID e051bc3f4302dfe");
                xhr.onload = function() {
                    var data = JSON.parse(xhr.responseText);

                    document.getElementById("id_photo").value = data.data.id;
                    document.getElementById("imageShow").setAttribute("src", data.data.link);
                };
                xhr.send(fd);

            }
        </script>
        
         <script type="text/javascript">
$(function() {
  $("#tagsearch").suggest({
    key: "AIzaSyDIO2lbCrilTAPn9ZBIU1PL6n46FxnqgEw"
  }).bind("fb-select", function(e, data) {
      $("#tagsearch").val(data.name +"(" + data.notable.name + ")");
  });
});
</script>


    </head>

    <body class="direction-left">

        <!------ HEADER (BEGIN) ---------------------------->
        <div class='header'>
            <div class='menu' style='float: right; margin-right:10px; margin-left:1px;'>
                <% if (user != null) {%>
                <a href="/MyCityWeb/addPost.jsp"><img src="/MyCityWeb/img/newPost.png" title='NEW POST' alt='NEW POST' /></a>
                <a href="/MyCityWeb/profilePage.jsp"><img src="/MyCityWeb/img/profile.png" title='PROFILE PAGE' alt='PROFILE PAGE' /></a>
                <% }%>
                <a href="/MyCityWeb/searchPost.jsp"><img src="/MyCityWeb/img/search.png" title='SEARCH FOR A LOCATION' alt='SEARCH FOR A LOCATION' /></a>             
                <a href="/MyCityWeb/home.jsp"><img src="/MyCityWeb/img/home.png" title='HOME PAGE' alt='HOME PAGE' /></a>
            </div>

        </div>	
        <!------- HEADER (END) -------------------------------->

        <div class='result-panel'>
            <div class='result-right'>

                <div id='map-canvas' style="height: 200px; width:100%; float:right; margin-bottom:10px; overflow:hidden; position:relative;">
                </div>

                <!-- NEW POST (BEGIN) -->

                <!-- POST FORM -->
                <div class='question'>
                    <div class='question-icons'>
                    </div>
                    <div class='answer'>

                        <form method='post' action='/MyCityWeb/Post/create' name='PostCreate' onsubmit="return  validateForm();">
                            <textarea class='question' autofocus='true' name="question" placeholder="Post message..."></textarea><br/>
                            <input type="text" class='answer'  style='width:100%;' name='nplace'  id="iplace" placeholder="Select a place..."  readonly/><br/>
                            
                    <input type="text" name="tags" id="tags" class="answer" placeholder="Add a tag...">
                    <br/>                           
                            <input type='file' id='uploadphoto' onchange="upload(this.files[0]);" title="Select for a file to add" name='photo' />
                            <img id="imageShow" src="" width="400px" height="300px" />
                            <input type="submit" id="subscribe-button" style='width:100%;' value="POST" />
                            <input type="text" name="loc_id" id="id_lat" style="display:none"/>
                            <input type="text" name="photo_id" id="id_photo" style="display:none"/>
                        </form>

                    </div>
                </div>



                <!-- /POST FORM -->

                <!-- NEW POST (END) -->


            </div>

            <!-------- SIDEBAR (BEGIN) --------------------->
            <div class='result-left'>


                <div class='divider'></div>
                <div class='title'><span class='title'>RECENT POSTS</span></div>
                <ul class='dic-result'>	
                    <%
                        if (posts.length > 0) {
                            for (PostTab post : posts) {
                                out.print("<li><a href='/MyCityWeb/Post/view/" + post.getPostId() + "'>");
                                out.print(post.getPostContent() + "</br>Date:"
                                        + post.getPostDate() + "</a></li>");
                            }
                        } else {
                            out.print("No posts");
                        }
                    %>
                </ul>


                <div class='divider'></div>
                <div class='title'><span class='title'>SEARCH FOR TAGS</span></div>
                <div>
                    <form action='/MyCityWeb/Search/byTag/' method='post'>
                        <input type='text' name='searchtag'  id="tagsearch" autocomplete="off" placeholder='Enter a tag...' />
                        <input type='submit' class='city-search' value='SEARCH' />
                    </form>
                </div>
            </div>
            <!-------- SIDEBAR (END) --------------------->

        </div>



    </body>
</html>
